<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>新建数据链路</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="./layui/css/layui.css" th:href="@{/layui/css/layui.css}" media="all">
    <link rel="stylesheet" href="./style/admin.css" th:href="@{/style/admin.css}" media="all">
    <link rel="stylesheet" href="./style/myself.css" th:href="@{/style/myself.css}" media="all">
    <!-- 让IE8/9支持媒体查询，从而兼容栅格 -->
    <!--[if lt IE 9]>
    <script src="./js/html5.min.js" th:src="@{/js/html5.min.js}"></script>
    <script src="./js/respond.min.js" th:src="@{/js/respond.min.js}"></script>
    <![endif]-->
    <script type="text/javascript" charset="utf-8" th:inline="javascript">
        let ctxPath = /*[[@{/}]]*/'';
    </script>
</head>
<body>
<div style="display: flex">
    <div style="width: 25%; padding: 15px; ">
        <div class="layui-row layui-col-space15">
            <div class="layui-col-md12">
                <div class="layui-card">
                    <div class="layui-card-header">节点</div>
                    <div class="layui-card-body" pad15>
                        <form class="layui-form" lay-filter="form">
                            <div class="layui-form-item">
                                <label class="layui-form-label">节点名称</label>
                                <div class="layui-input-inline">
                                    <select name="fromNode" lay-filter="fromNode" id="initNodeSelect">

                                    </select>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <button class="layui-btn" lay-submit lay-filter="createNode">添加节点</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="layui-card">
                    <div class="layui-card-header">关系 <span style="font-size: 13px">(需要先添加节点后才可选)</span></div>
                    <div class="layui-card-body" pad15>
                        <form class="layui-form" lay-filter="LinkForm">
                            <div class="layui-form-item">
                                <label class="layui-form-label">起始节点</label>
                                <div class="layui-input-inline">
                                    <select name="fromNode" lay-filter="fromNode" id="fromNodeSelect"></select>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">结束节点</label>
                                <div class="layui-input-inline">
                                    <select name="toNode" lay-filter="toNode" id="toNodeSelect"></select>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">线条颜色</label>
                                <div class="layui-input-inline">
                                    <select name="linkColor" lay-filter="linkColor">
                                        <option value="black">黑色</option>
                                        <option value="blue">蓝色</option>
                                        <option value="yellow">黄色</option>
                                        <option value="green">绿色</option>
                                    </select>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">线条类型</label>
                                <div class="layui-input-inline">
                                    <select name="linkType" lay-filter="linkType">
                                        <option value="Link">直线</option>
                                        <option value="AutoFoldLink">自动</option>
                                        <option value="CurveLink">曲线</option>
                                        <option value="ArcLink">圆弧线</option>
                                    </select>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <button class="layui-btn" lay-submit lay-filter="createLink">添加关系</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="layui-card">
                    <div class="layui-card-header">生成链路</div>
                    <div class="layui-card-body" pad15>
                        <form class="layui-form" lay-filter="deleteNodeForm">
                            <div class="layui-form-item">
                                <label class="layui-form-label">链路名称</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="dataLinkName" lay-verify="dataLinkName"
                                           lay-verType="tips" placeholder="请输入链路名称"
                                           autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item layui-form-text">
                                <label class="layui-form-label">备注信息</label>
                                <div class="layui-input-block">
                                        <textarea name="remark" lay-verify="remark" placeholder="请输入备注信息"
                                                  class="layui-textarea"></textarea>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <button class="layui-btn" lay-submit lay-filter="createDataLink">生成链路</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div id="divId" style="height:calc(100vh - 50px); width: 71%; padding: 15px;"></div>
</div>

<script src="./js/common.js" th:src="@{/js/common.js}" charset="utf-8"></script>
<script src="./js/jquery.min.js" th:src="@{/js/jquery.min.js}" charset="utf-8"></script>
<script src="./js/jquery.base64.js" th:src="@{/js/jquery.base64.js}" charset="utf-8"></script>
<script src="./layui/layui.js" th:src="@{/layui/layui.js}" charset="utf-8"></script>
<script charset="utf-8" th:inline="javascript" type="module">
    layui.config({
        base: ctxPath //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'form', 'element', 'layer'], function () {
        let admin = layui.admin;
        let form = layui.form;
        form.render();
        let nodeLinkData = []
        let sourceItems = [];

        form.on('submit(createNode)', function (data) {
            if(nodeLinkData.length > 0){
                for (let i = 0; i < nodeLinkData.length; i++) {
                    //校验是否存在节点
                    if(nodeLinkData[i].fromNode === data.field.fromNode){
                        layer.msg('已存在该节点名称，请重新输入！');
                        return false;
                    }
                }
            }

            for (let i = 0; i < sourceItems.length; i++) {
                if(sourceItems[i].connName == data.field.fromNode){
                    console.log("sourceItems[i]:" + JSON.stringify(sourceItems[i]))
                    data.field.dbId = sourceItems[i].id;
                    data.field.dbType = sourceItems[i].dbType;
                    let img = "";
                    if (sourceItems[i].dbType === 'MySQL') {
                        img = ctxPath + 'images/db/mysql-small.png';
                    }
                    if (sourceItems[i].dbType === 'Oracle') {
                        img = ctxPath + 'images/db/oracle-small.png';
                    }
                    if (sourceItems[i].dbType === 'Redis') {
                        img = ctxPath + 'images/db/redis-small.png';
                    }
                    if (sourceItems[i].dbType === 'Mongo') {
                        img = ctxPath + 'images/db/mongo-small.png';
                    }
                    createNode(0, 0, img, data.field.fromNode, sourceItems[i].text)
                    break;
                }
            }

            //不存在则放入数据中
            data.field.links = [];
            nodeLinkData.push(data.field)

            console.log("调用createNode完成")
            layer.msg('创建成功！');

            //动态改变下拉选项
            updateNodeSelect(data.field.fromNode)
            return false;
        })

        form.on('submit(createDataLink)', function (data) {
            console.log("链路名称：" + data.field.dataLinkName)

            if (data.field.dataLinkName == undefined || data.field.dataLinkName == ""){
                layer.msg('链路名称不能为空！', {icon: 5, shift: 6});
                return false;
            }
            if (data.field.dataLinkName.length < 4) {
                layer.msg('链路名称不能少于4个字！', {icon: 5, shift: 6});
                return false;
            }
            if (data.field.dataLinkName.length > 30){
                layer.msg('链路名称不能多于30个字！', {icon: 5, shift: 6});
                return false;
            }

            nodeLinkData.forEach(function(item) {
                let node = getNode(item.fromNode)
                item.nodeX = node.x
                item.nodeY = node.y
            })

            console.log("链路数据：" + JSON.stringify(nodeLinkData))

            admin.req({
                type: 'post',
                url: ctxPath + 'jtopo/createDataLink',
                data: {dataLinkJson: JSON.stringify(nodeLinkData),
                    dataLinkName: data.field.dataLinkName,
                    remark: data.field.remark},
                dataType: 'json',
                headers: {
                    [[${_csrf.headerName}]]: [[${_csrf.token}]]
                },
                success: function (result) {
                    let data = result.data;
                    if (data === webConst.SUCCESS) {
                        layer.msg('链路创建成功！', {icon: 6});
                    } else if (data === webConst.EXIST) {
                        layer.msg('该链路名称已存在，换个名称试试吧！', {icon: 5, shift: 6});
                    } else {
                        layer.msg('链路创建失败！', {icon: 5, shift: 6});
                    }
                },
                error: function () {
                    layer.msg('系统错误！', {icon: 5, shift: 6});
                }
            });

            return false;
        })

        form.on('submit(createLink)', function (data) {
            console.log("连线表单内容：" + JSON.stringify(data.field))

            if(data.field.fromNode === data.field.toNode){
                layer.msg('起始节点和结束节点相同，请重新选择！');
                return false;
            }


            nodeLinkData.forEach(function(item) {
                if(data.field.fromNode === item.fromNode){
                    if(item.links.length > 0){
                        item.links.forEach(function(link) {
                            if(link.fromNode === data.field.fromNode && link.toNode === data.field.toNode){
                                layer.msg('这两个节点已经连过线，请重新选择！');
                                return  false
                            }else{
                                let fromNode = getNode(data.field.fromNode)
                                let toNode = getNode(data.field.toNode)
                                item.links.push(data.field)
                                linkNode(fromNode, toNode, "备注",  data.field.linkType, data.field.linkColor, "0")
                                console.log("连线结束")
                                layer.msg('连接成功！');
                            }
                        })
                    }else{
                        let fromNode = getNode(data.field.fromNode)
                        let toNode = getNode(data.field.toNode)
                        item.links.push(data.field)
                        linkNode(fromNode, toNode, "备注",  data.field.linkType, data.field.linkColor, "0")
                        console.log("连线结束")
                        layer.msg('连接成功！');
                    }
                }
            })

            console.log("Data:" + JSON.stringify(nodeLinkData))

            return false;
        })

        function updateNodeSelect(fromNode){
            let toNodeSelect = document.getElementById(`toNodeSelect`)
            let option1 = new Option(fromNode, fromNode);
            toNodeSelect.options.add(option1);
            form.render();

            let fromNodeSelect = document.getElementById(`fromNodeSelect`)
            let option = new Option(fromNode, fromNode);
            fromNodeSelect.options.add(option);
            form.render();

            JtopoRender()
        }

        function initNodeselect(item){
            let initNodeSelect = document.getElementById(`initNodeSelect`)
            let option = new Option(item, item);
            initNodeSelect.options.add(option);
            form.render();
        }

        admin.req({
            type: 'get',
            url: ctxPath + 'monitor-db/get-monitor-db-list',
            data: {current: 1, size: 10000},
            dataType: 'json',
            headers: {
                [[${_csrf.headerName}]]: [[${_csrf.token}]]
            },
            success: function (result) {
                console.log("res:" + JSON.stringify(result))
                sourceItems = result.data.records
                for (let i = 0; i < result.data.records.length; i++) {
                    console.log("item:" + result.data.records[i].connName)
                    initNodeselect(result.data.records[i].connName)
                }
            }
        })

    });

    // 替换成实际路径
    import {Stage, Layer, Node, Link, Tooltip, PopupMenu, Shape, FoldLink, randomColor,
        AutoFoldLink, BezierLink, ArcLink, CurveLink, RatioNode, VideoNode, TextNode, CircleNode}
        from '../../phoenix-ui/lib/phoenix/core.js';

    const stage = new Stage('divId');
    let jtopoLayer = new Layer();
    stage.addChild(jtopoLayer);

    let nodes = [];
    let links = [];

    function createNode(x, y, img, name, text) {
        let node = new Node(name);
        node.setImage(img, true);
        //设置node坐标，宽高
        if(x == 0 && y == 0){
            x = -400
            y = -200
        }
        node.translate(x, y);
        node.resizeTo(50, 50);

        // 鼠标指向小提示
        let tooltip = new Tooltip(stage);
        tooltip.setHtml(text);

        //设置悬浮显示内容
        node.on('mousemove', function () {
            let input = stage.inputSystem;
            tooltip.showAt(input.x, input.y);
        });

        nodes.push(node);
        JtopoRender()
        console.log("完成创建")
    }

    function linkNode(nodeA, nodeZ, text, linkType, linkColor, effects) {
        console.log("开始连线")
        let link = new Link(text,nodeA,nodeZ);
        if(linkType === 'AutoFoldLink'){
            link = new AutoFoldLink(text,nodeA,nodeZ);
        }
        if(linkType === 'CurveLink'){
            link = new CurveLink(text,nodeA,nodeZ);
        }
        if(linkType === 'ArcLink'){
            link = new ArcLink(text,nodeA,nodeZ);
        }
        if(linkType === 'BezierLink'){
            link = new BezierLink(text,nodeA,nodeZ);
        }
        link.css({
            'lineWidth': 2,
            strokeStyle: linkColor
        });

        //设置箭头
        link.setBegin(nodeA, 'rm');
        link.setEnd(nodeZ, 'lm');
        let endArrow = new Node;
        endArrow.resizeTo(12, 12);
        endArrow.setShape(Shape.Polygon(3));
        endArrow.css({
            lineWidth: 1,
            strokeStyle: linkColor
        });
        link.setEndArrow(endArrow);

        // 给link，增加’流动特效'
        if(effects === '1'){
            stage.effectSystem.flow(link, { lineDash: [8, 2] }).play();
        }

        links.push(link);
        JtopoRender()
        console.log("连线完成")
    }

    function getNode(name){
        for (let k = 0; k < nodes.length; k++) {
            if(nodes[k]._text == name){
                console.log("getNode 获取到节点:" + nodes[k]._text)
                return nodes[k]
            }
        }
    }

    function JtopoRender(){
        jtopoLayer.addChilds(nodes);
        jtopoLayer.addChilds(links);
        stage.show();
    }

    window.onload = function() {
        // 页面加载完成后执行的代码
        jtopoLayer.addChilds(nodes);
        jtopoLayer.addChilds(links);
        stage.show();
    };
</script>

</body>
</html>